package com.fhx.core.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.telephony.TelephonyManager
import android.util.Log
import com.fhx.core.AppContext
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader

object NetworkUtil {
    fun isNetworkAvailable(): Boolean {
        try {
            val cm =
                AppContext.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val info = cm.activeNetworkInfo
            return info != null && info.isConnected
        } catch (e: Exception) {
            e.printStackTrace()
            return false
        }
    }


    fun isWifi(): Boolean {
        val networkType = getNetworkType()
        return networkType == NETWORK_TYPE_WIFI
    }


    const val NETWORK_TYPE_UNCONNECT = -1
    const val NETWORK_TYPE_UNKNOWN = 0
    const val NETWORK_TYPE_WIFI = 1
    const val NETWORK_TYPE_2_G = 2
    const val NETWORK_TYPE_3_G = 3
    const val NETWORK_TYPE_4_G = 4
    const val NETWORK_TYPE_5_G = 5

    fun getNetworkType(): Int {
        try {
            val cm =
                AppContext.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val activeNetInfo = cm.activeNetworkInfo
            if (activeNetInfo != null && activeNetInfo.isConnected) {
                val type = activeNetInfo.type
                if (type == ConnectivityManager.TYPE_WIFI || type == 9) { // ConnectivityManager.TYPE_ETHERNET=9高版本才有这个变量
                    return NETWORK_TYPE_WIFI
                } else if (type == ConnectivityManager.TYPE_MOBILE) {
                    return getMobileNetType(activeNetInfo.subtype)
                } else {
                    return NETWORK_TYPE_UNKNOWN
                }
            } else {
                return NETWORK_TYPE_UNCONNECT
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return NETWORK_TYPE_UNCONNECT
        }
    }

    fun getMobileNetType(networkType: Int): Int {
        return when (networkType) {
            TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> NETWORK_TYPE_2_G
            TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> NETWORK_TYPE_3_G
            TelephonyManager.NETWORK_TYPE_LTE -> NETWORK_TYPE_4_G
            TelephonyManager.NETWORK_TYPE_NR -> NETWORK_TYPE_5_G
            else -> NETWORK_TYPE_UNKNOWN
        }
    }

    /**
     * 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
     */
    fun ping(): Boolean {
        var result: String? = null
        try {
            val ip = "www.baidu.com" // ping 的地址，可以换成任何一种可靠的外网
            val p =
                Runtime.getRuntime().exec("ping -c 3 -w 100 $ip") // ping网址3次
            // 读取ping的内容，可以不加
            val input: InputStream = p.inputStream
            val `in` = BufferedReader(InputStreamReader(input))
            val stringBuffer = StringBuffer()
            var content: String? = ""
            while (`in`.readLine().also { content = it } != null) {
                stringBuffer.append(content)
            }
            Log.d("------ping-----", "result content : $stringBuffer")
            // ping的状态
            val status = p.waitFor()
            if (status == 0) {
                result = "success"
                return true
            } else {
                result = "failed"
            }
        } catch (e: IOException) {
            result = "IOException"
        } catch (e: InterruptedException) {
            result = "InterruptedException"
        } finally {
            Log.d("----result---", "result = $result")
        }
        return false
    }
}
